<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-alert title="注意：只允许为第三级分类设置相关参数"
                      show-icon :closable="false" type="warning"></el-alert>

            <!--            级联选择器区域-->
            <el-row class="catopt">
                <el-col>
                    <span>选择商品分类：</span>
                    <el-cascader v-model="cateSelectKeys"
                                 :props="catePorps" :options="cateList"
                                 expand-trigger="hover" clearable @change="cascaderChange">
                    </el-cascader>
                </el-col>
            </el-row>

            <!--            tab 页签区域-->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" :disabled="isbtnDisable" @click="addPrams">添加参数</el-button>
                    <el-table :data="manyTableData" border>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" closable
                                        :key="i" v-if="scope.row.attr_vals.length !== 0"
                                        @close="handleClose(i,scope.row)">
                                    {{item}}
                                </el-tag>
                                <!--   动态编辑的文本输入框和按钮-->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="tagInput"
                                        size="small"
                                        @blur="handleInputConfirm(scope.row)" style="width: 120px">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini"
                                           @click="editClick(scope.row.attr_id)">编辑
                                </el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                           @click="deleteClick(scope.row.attr_id)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" :disabled="isbtnDisable" @click="addPrams">添加属性</el-button>
                    <el-table :data="onlyTableData" border>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals"
                                        :key="i" v-if="scope.row.attr_vals.length !== 0" closable
                                        @close="handleClose(i,scope.row)">
                                    {{item}}
                                </el-tag>
                                <!--   静态编辑的文本输入框和按钮-->
                                <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="tagInput"
                                        size="small"
                                        @blur="handleInputConfirm(scope.row)" style="width: 120px">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+
                                    New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini"
                                           @click="editClick(scope.row.attr_id)">编辑
                                </el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                           @click="deleteClick(scope.row.attr_id)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

            <!--            添加分类参数的弹框区域-->
            <el-dialog
                    :visible.sync="addPramsDialogVisible"
                    :title="'添加'+ cateName"
                    width="50%" @close="addClose">
                <el-form :model="ParamsFrom" :rules="ParamsFromRules" label-width="80px" ref="ParamsFrom">
                    <el-form-item :label="cateName" prop="attr_name">
                        <el-input v-model="ParamsFrom.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <span class="dialog-footer" slot="footer">
                <el-button @click="addPramsDialogVisible = false">取 消</el-button>
                <el-button @click="addPramsReady" type="primary">确 定</el-button>
            </span>
            </el-dialog>

            <!--            修改分类参数的弹框-->
            <el-dialog
                    :visible.sync="editPramsDialogVisible"
                    :title="'修改'+ cateName"
                    width="50%" @close="editClose">
                <el-form :model="editParamsFrom" :rules="editParamsFromRules" label-width="80px" ref="editParamsFrom">
                    <el-form-item :label="cateName" prop="attr_name">
                        <el-input v-model="editParamsFrom.attr_name"></el-input>
                    </el-form-item>
                </el-form>
                <span class="dialog-footer" slot="footer">
                <el-button @click="editPramsDialogVisible = false">取 消</el-button>
                <el-button @click="editReady" type="primary">确 定</el-button>
            </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
  export default {
    name: "Params",
    data() {
      return {
        cateList: [],
        cateSelectKeys: [],//级联选择器双向绑定的数组数据
        catePorps: {//配置项
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        manyTableData: [],
        onlyTableData: [],
        activeName: 'many',//默认被激活的页签
        addPramsDialogVisible: false,
        editPramsDialogVisible: false,
        ParamsFrom: {//添加分类的表单
          attr_name: ''
        },
        ParamsFromRules: {
          attr_name: [{required: true, message: '请输入正确的参数', trigger: 'blur'}]
        },
        //修改分类的表单
        editParamsFrom: {
          attr_name: ''
        },
        editParamsFromRules: {
          attr_name: [{required: true, message: '请输入正确的参数', trigger: 'blur'}]
        },
        attr_id: '',
        // inputVisible: false,//文本框控制的布尔值
        // inputValue: '',//文本框绑定的值
      }
    },
    computed: {
      //根据用户选择的级联选择器是否为三级判定按钮可否点击
      isbtnDisable() {
        if (this.cateSelectKeys.length === 3) {
          return false
        } else {
          return true
        }
      },
      //获取到级联选择器的三级分类的id
      cateId() {
        if (this.cateSelectKeys.length === 3) {
          return this.cateSelectKeys[2]
        } else {
          return null
        }
      },
      //缓存当前页签name值
      cateName() {
        if (this.activeName == 'many') {
          return '动态参数'
        } else {
          return '静态属性'
        }
      }
    },
    methods: {
      //获取所有的商品列表信息
      async getCateList() {
        const {data: res} = await this.$http.get('categories')
        if (res.meta.status !== 200) return this.$message.error('获取商品列表失败')
        this.cateList = res.data
      },
      //级联选择器改变
      cascaderChange() {
        //当用户选择之后 判断长度是否为3 不然清空绑定的数组数据
        if (this.cateSelectKeys.length == 3) {
          // console.log(this.cateSelectKeys);
          this.getCateParamsList()//根据所选分类的id，和当前对应的面板获取对应的参数
        }else{
          this.cateSelectKeys = []
          this.manyTableData = []
          this.onlyTableData = []
          this.getCateParamsList()
        }


      },
      //页签点击时触发
      handleClick() {
        this.getCateParamsList()
      },
      //点击添加参数/属性按钮
      addPrams() {
        this.addPramsDialogVisible = true
      },

      // 获取动态静态的参数列表数据
      async getCateParamsList() {
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeName}})
        if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
        //分割动态静态下的attr_vals 参数   注意''分割后会返回一个[''],所以要进行判断
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          //给遍历到的数据添加一个控制文本框显示与隐藏的值
          item.inputVisible = false
          //控制绑定的文本值
          item.inputValue = ''
        })
        console.log(res.data)
        //判断获取到的数据是many动态参数的还是only静态属性的  分别储存起来
        if (this.activeName == 'many') {
          this.manyTableData = res.data
        } else {
          this.onlyTableData = res.data
        }
      },
      //添加分类弹框的关闭
      addClose() {
        this.$refs.ParamsFrom.resetFields()//重置表单
      },
      //添加分类确定的点击
      addPramsReady() {
        this.getAddParams()
      },
      //修改弹框确定的点击
      editReady() {
        this.getEditParams()
        this.editPramsDialogVisible = false
      },
      //编辑按钮的点击
      async editClick(attr_id) {
        //根据三级分类id 和  attr_id 查询点击行的数据
        this.attr_id = attr_id
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,
          {params: {attr_sel: this.activeName}})
        if (res.meta.status !== 200) return
        this.editParamsFrom = res.data
        this.editPramsDialogVisible = true
      },
      //点击删除按钮
      async deleteClick(attr_id) {
        const configresult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        //如果为点击确定 返回configresult为confirm字符串   取消则返回cancel字符串
        if (configresult !== 'confirm') {
          return this.$message.info('已经取消了删除')
        } else {
          //发起删除请求
          const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
          if (res.meta.status !== 200) return this.$message.error('删除参数失败')
          this.$message.success('删除参数成功')
          this.getCateParamsList()
        }
      },
      //关闭修改对话框时触发  重置表单
      editClose() {
        this.$refs.editParamsFrom.resetFields()
      },

      // 添加动态参数或者静态属性的请求
      getAddParams() {
        this.$refs.ParamsFrom.validate(async valid => {
          if (!valid) return this.$message.error('请认真填写参数项')
          const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.ParamsFrom.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 201) {
            return this.$message.error('添加失败')
          } else {
            this.$message.success('添加成功')
            this.addPramsDialogVisible = false
            this.getCateParamsList()
          }
        })
      },

      //修改提交参数的请求
      getEditParams() {
        this.$refs.editParamsFrom.validate(async valid => {
          if (!valid) return
          const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.attr_id}`,
            {
              attr_name: this.editParamsFrom.attr_name,
              attr_sel: this.activeName
            })
          if (res.meta.status !== 200) return this.$message.error('参数更新失败')
          this.$message.success('参数更新成果')
          this.getCateParamsList()
        })
      },
      //文本框失去焦点时触发
      async handleInputConfirm(row) {
        if (row.inputValue.trim().length === 0) {
          row.inputValue = ''
          row.inputVisible = false
          return
        } else {//没有return 则证明输入正确  发送把新增的inputValue添加进去数组
          row.attr_vals.push(row.inputValue)
          row.inputValue = ''
          row.inputVisible = false
          //发送网络请求 保存到数据库中 （编辑那个网络请求）
          this.setPramsItem(row)
        }

      },
      //文本框按钮点击时触发
      showInput(row) {
        row.inputVisible = true
        this.$nextTick(_ => { //点击后还是button按钮  文本框还没渲染完， 所以要等渲染完才调用获取焦点
          this.$refs.tagInput.$refs.input.focus();
        });
      },
      // 文本框删除的点击
      async handleClose(i, row) {
        row.attr_vals.splice(i, 1)
        this.setPramsItem(row)
      },
      //修改三级属性下参数的值的改变的请求
      async setPramsItem(row) {
        const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')//后台只接收字符串 所以要转化
        })
        if (res.meta.status !== 200) return this.$message.error('删除参数项失败')
        this.$message.success('删除参数项成功')
      }
    },
    created() {
      this.getCateList()
    }
  }
</script>

<style scoped>
    .el-tag {
        margin: 15px 20px;

    }
</style>